from operator import index

import jsonpath
import pytest
import yaml

from commons.assertion import equals_assert, include_assert, not_equals_assert
from commons.global_info import dict_var
from commons.sessions import Session
from utils.encrypt_tool import md5_data
from utils.replace_both import value_replace_var
from yaml_funcs import extract_var

session = Session()
@pytest.fixture(scope="session")
def login_auth():
    res = session.request(
        "POST",
        "/auth/oauth/token",
        params={
            "grant_type": "password",
            "client_id": "HHIKARr5Tx2cek4O",
            "username": "15732069727",
            "password": md5_data("q123456")
        })
    print(res.json())
    assert res.status_code == 200
    assert "access_token" in res.json()
    access_token = jsonpath.jsonpath(res.json(), "$.access_token")[0]
    session.headers={
        "Authorization": "Bearer " + access_token
    }


    uid = jsonpath.jsonpath(res.json(), "$..uid")[0]
    dict_var["uid"]=uid
    print(dict_var)
    return  session

def pytest_yaml_run_step(item):
    print('用例名称', item.name)
    print('当前步骤', item.current_step)
    for leve_one_k,leve_one_v in item.current_step.items():
        print("开始打印《当前步骤》参数以及参数值")
        print(leve_one_k,leve_one_v)
        if leve_one_k=="request":
            new_item=value_replace_var(leve_one_v)
            print("替换完后显示的数据：",new_item)

            item.res=session.request(**new_item)
            print(f"用例名称为{item.name}的响应结果",item.res.json())
        if leve_one_k=="extract":
            extract_var(leve_one_v,item.res)
        if leve_one_k=="validate":
            for leve_two_k,leve_two_v in leve_one_v.items():
                if leve_two_k == "equals":
                    for leve_three_k,leve_three_v in leve_two_v.items():
                        print(f">>>>>>>>>>>>>>>>>>>>{leve_three_k}{leve_three_v}")
                        equals_assert(leve_three_v[0],leve_three_v[1],item.res,leve_three_v[2],leve_three_k)

                if leve_two_k=="not equals":
                    for leve_noteq_k, leve_noteq_v in leve_two_v.items():
                        not_equals_assert(leve_noteq_v[0],leve_noteq_v[1],item.res,leve_noteq_v[2],leve_noteq_k)
                if leve_two_k=="in":
                    for leve_in_k, leve_in_v in leve_two_v.items():
                        include_assert(leve_in_v[0],leve_in_v[1],item.res,leve_in_v[2],index=leve_in_v[3],msg=leve_in_k)
    print("添加完提取变量及变量值后dict_valr=",dict_var)
